package larrys.pomodoro.controller.pages.common;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;

import larrys.pomodoro.Constant;
import larrys.pomodoro.domain.service.PomodoroUserService;
import larrys.pomodoro.form.SignupForm;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class SignupController {

	private static Log logger = LogFactory.getLog(SignupController.class);

	@Autowired
	private MessageSource messages;

	@Autowired
	private Validator validator;

	@Autowired
	private PomodoroUserService userService;

	@RequestMapping(value = "/signup", method = RequestMethod.GET)
	public String signupGet() {
		return "common/signup";
	}

	@RequestMapping(value = "/signup", method = RequestMethod.POST)
	public String signupPost(SignupForm signupForm, Model model, Locale locale,
			HttpServletRequest request, HttpServletResponse response) {
		boolean invalid = false;
		for (ConstraintViolation<SignupForm> violation : validator
				.validate(signupForm)) {
			invalid = true;
			model.addAttribute(violation.getPropertyPath().toString()
					+ Constant.FORM_ERROR_SUFFIX, violation.getMessage());
		}
		String password = signupForm.getPassword();
		String confirm = signupForm.getConfirmPassword();
		if (password != null && !password.equals(confirm)) {
			invalid = true;
			model.addAttribute("confirmpassword" + Constant.FORM_ERROR_SUFFIX,
					messages.getMessage("message_confirmpasswordnotmatch",
							null, locale));
		}
		if (userService.isUserEmailExist(signupForm.getEmail())) {
			invalid = true;
			model.addAttribute("email" + Constant.FORM_ERROR_SUFFIX,
					messages.getMessage("message_emailexists", null, locale));
		}
		if (invalid) {
			return "common/signup";
		} else {
			userService.addUser(signupForm);
			try {
				String encodedEmail = "?email="
						+ URLEncoder.encode(signupForm.getEmail(), "UTF-8");
				response.sendRedirect(request.getContextPath()
						+ "/pages/loginpage" + encodedEmail);
			} catch (IOException e) {
				logger.error(
						"Exception threw while redirecting to /pages/loginpage",
						e);
				throw new RuntimeException(e);
			}
			return "common/login";
		}
	}
}
